//版权说明：修正按钮、文本位置，版本号：3.0，生成日期：2021-12-26，作者：房晓童，内容：入侵检测页面逻辑
// 功能：实现入侵检测页面的各控件的初始化代码逻辑，与其它文件的关系：activity_main.xml为其布局
package com.example.safehome;

import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.app.Notification;
import android.app.NotificationManager;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.sqlite.SQLiteDatabase;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;


import org.litepal.tablemanager.Connector;

import java.util.Date;

public class BreakInSensorActivity extends AppCompatActivity implements View.OnClickListener {

    //音频播放器声明
    private MediaPlayer mediaPlayer = new MediaPlayer();

    //控件声明
    TextView textViewSystemStatus;
    TextView textViewBreakInPosition;
    TextView textViewIsBreakIn;
    TextView textViewIsRunning;
    Button buttonDetect;
    Button buttonQuit;
    Button buttonTest;
    Button buttonRecord;
    Button buttonCall;
    BreakInSensor breakInSensor = new BreakInSensor();

    //是否正在检测
    boolean isDetect = false;

    //
    private NotificationManager mNManager;
    private Notification notify1;
    private static final int NOTIFYID_1 = 1;


    @Override
    protected void onCreate(Bundle savedInstanceState) {

        //入侵窗口生成
        super.onCreate(savedInstanceState);
        setContentView(R.layout.break_in_activity_main);
        textViewSystemStatus = (TextView) findViewById(R.id.tv_system_status);
        textViewBreakInPosition = (TextView) findViewById(R.id.tv_position);
        textViewIsBreakIn = (TextView) findViewById(R.id.tv_isbreakin);
        textViewIsRunning = (TextView) findViewById(R.id.tv_isrunning);
        buttonDetect = (Button) findViewById(R.id.bt_detect);
        buttonQuit = (Button) findViewById(R.id.bt_quit);
        buttonTest = (Button) findViewById(R.id.bt_test);
        buttonRecord = (Button) findViewById(R.id.bt_record);
        buttonCall = (Button) findViewById(R.id.bt_call110);

        //为按钮添加监听
        buttonRecord.setOnClickListener(this);
        buttonDetect.setOnClickListener(this);
        buttonQuit.setOnClickListener(this);
        buttonTest.setOnClickListener(this);
        buttonCall.setOnClickListener(this);

        //报警音频初始化与设置
        mediaPlayer = MediaPlayer.create(this, R.raw.warning);
        mediaPlayer.setLooping(true);

        //菜单标题栏
        Toolbar toolBar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolBar);
        ActionBar actionBar = getSupportActionBar();
        if(actionBar != null){
            actionBar.setDisplayHomeAsUpEnabled(true);
        }
        SQLiteDatabase warningRecardDataBase = Connector.getDatabase();

        //写数据库
        textViewBreakInPosition.addTextChangedListener(new TextWatcher() {

            @Override
            public void beforeTextChanged(CharSequence charSequence, int start, int count, int after) {

                // charSequence为在你按键之前显示的字符串  start为新字符串与charSequence开始出现差异的下标
                // count表示原字符串的count个字符  after表示将会被after个字符替换
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int start, int before, int count) {

                // 按键之前字符串的start位置的before个字符已经被count个字符替换形成新字符串charSequence
            }

            @Override
            public void afterTextChanged(Editable editable) {

                // afterTextChanged中 editable为EditText显示的内容
                //入侵发生检测写入数据库
                BreakInWarningRecord record = new BreakInWarningRecord();
                record.setBreakInTime(new Date(java.lang.System.currentTimeMillis()));
                record.setBreakInPlace(breakInSensor.getBreakInPosition());
                record.setIsCallPolice(false);
                record.setDetail("");
                record.saveThrows();
            }
        });

        //音频权限获取
        if (ContextCompat.checkSelfPermission(BreakInSensorActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(BreakInSensorActivity.this, new String[]{
                    Manifest.permission.WRITE_EXTERNAL_STORAGE
            }, 1);
        }
    }

    //权限获取
    public void onRequestPermissionResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {
            case 1:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    break;
                }
                else {
                    Toast.makeText(this, "拒绝权限将无法访问程序", Toast.LENGTH_SHORT).show();
                    finish();
                }
                break;
            default:
        }
    }

    //返回键设置
    public boolean onOptionsItemSelected(MenuItem item){
        switch (item.getItemId()){
            case android.R.id.home:
                breakInSensor.quit();
                isDetect = false;
                textViewIsRunning.setText("系统未运行");
                mediaPlayer.pause();
                textViewIsBreakIn.setText("");
                textViewBreakInPosition.setText("");
                finish();
                break;
            default:
                break;
        }
        return true;
    }

    //入侵界面按钮逻辑
    public void onClick(View v) {
        switch (v.getId()) {

            //开始检测按钮逻辑
            case R.id.bt_detect:
                breakInSensor.detect();
                isDetect = true;
                String Status, breakInPosition, isBreakIn, isRunning;

                //启动后台检测服务

                //状态正常
                if (breakInSensor.getStatus()) {
                    Status = "正常";
                    if (breakInSensor.isBreakIn()) {

                        //开始检测状态文本
                        textViewIsBreakIn.setText("房屋被入侵");
                        textViewBreakInPosition.setText(breakInSensor.getBreakInPosition());
                        mediaPlayer.setLooping(true);
                        mediaPlayer.start();

                    }
                    else {
                        textViewIsBreakIn.setText("房屋未被入侵");
                    }
                }
                else {
                    Status = "异常";
                }
                textViewSystemStatus.setText(Status);
                textViewIsRunning.setText("系统运行中...");
                break;

            //退出检测按钮逻辑
            case R.id.bt_quit:
                breakInSensor.quit();
                isDetect = false;
                textViewIsRunning.setText("系统未运行");
                mediaPlayer.pause();
                textViewIsBreakIn.setText("");
                textViewBreakInPosition.setText("");
                break;

            //检测记录按钮逻辑
            case R.id.bt_record:
                Intent intent = new Intent(BreakInSensorActivity.this, BreakInRecordActivity.class);
                startActivity(intent);
                break;

            //生成入侵
            case R.id.bt_test:
                breakInSensor.test();
                if (isDetect == true) {
                    if (breakInSensor.getStatus()) {
                        Status = "正常";
                        if (breakInSensor.isBreakIn()) {
                            textViewIsBreakIn.setText("房屋被入侵");
                            textViewBreakInPosition.setText(breakInSensor.getBreakInPosition());
                            mediaPlayer.setLooping(true);
                            mediaPlayer.start();
                        }
                        else {
                            textViewIsBreakIn.setText("房屋未被入侵");
                        }
                    }
                    else
                        Status = "异常";
                }
                break;

            //拨打报警电话按钮
            case R.id.bt_call110:
                Intent intent_call = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + 110));
                startActivity(intent_call);

            default:
                break;
        }
    }
}
